package com.wzh.websocket.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;


/**
 * @Author zh wang
 * @Create 2025/5/16 19:14
 */
public class UserIdInterceptor implements HandshakeInterceptor {
    private static final Logger log = LoggerFactory.getLogger(UserIdInterceptor.class);

    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response,
                                   WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) {
        // 转换请求类型
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            log.info("用户连接: {}", servletRequest.getServletRequest());
            // 从URL参数获取用户ID
            String userId = servletRequest.getServletRequest().getParameter("userId");
            log.info("用户连接ID: {}", userId);
            // 存入会话属性
            attributes.put("userId", userId);
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}